var data = [
{"id":1,name:"超级管理员","authorization":[100,300,400]},
{"id":2,name:"开发者","authorization":[300,400]},
{"id":3,name:"体验者","authorization":[100,400]},
{"id":4,name:"一般用户","authorization":[100,300,400]},
{"id":5,name:"超级VIP用户","authorization":[300,400]},
{"id":6,name:"超级管理员","authorization":[100,400,5001]},
{"id":7,name:"开发者","authorization":[100,300,400,5002]},
{"id":8,name:"体验者","authorization":[100,400]},
{"id":9,name:"一般用户","authorization":[300,400]},
{"id":10,name:"超级VIP用户","authorization":[100,300]},
{"id":11,name:"超级管理员","authorization":[100,300,400]},
{"id":12,name:"开发者","authorization":[100,300,400]},
{"id":13,name:"体验者","authorization":[100,300,400]},
{"id":14,name:"一般用户","authorization":[100,300,400]},
{"id":15,name:"超级VIP用户","authorization":[100,300,400]},
{"id":16,name:"超级管理员","authorization":[100,300,400]},
{"id":17,name:"开发者","authorization":[100,300,400]},
{"id":18,name:"体验者","authorization":[100,300,400]},
{"id":19,name:"一般用户","authorization":[100,300,400]},
{"id":20,name:"超级VIP用户","authorization":[100,300,400]},
{"id":21,name:"超级管理员","authorization":[100,300,400]},
{"id":22,name:"开发者","authorization":[100,300,400]},
{"id":23,name:"体验者","authorization":[100,300,400]},
{"id":24,name:"一般用户","authorization":[100,300,400]},
{"id":25,name:"超级VIP用户","authorization":[100,300,400]},
{"id":26,name:"超级管理员","authorization":[100,300,400]},
{"id":27,name:"开发者","authorization":[100,300,400]},
];

var treeData = [
    {
        "id":"100",
        "text":"操作员管理"
    },
    {
        "id":"200",
        "text":"服务器管理"
    },
    {
        "id":"300",
        "text":"用户管理",
        "state":{
            "opened":true
        },
        "children":[
            {
                "id":"3001",
                "text":"用户管理",
            }
        ]
    },
    {
        "id":"400",
        "text":"产品管理"
    },
    {
        "id":"500",
        "text":"订单管理",
        "state":{
            "opened":true
        },
        "children":[
            {
                "id":"5001",
                "text":"订单记录"
            },
            {
                "id":"5002",
                "text":"支付记录"
            }
        ]
    }
];

var roles_manager = {
    el:"",
    data:[],
    is_select:false,
    // 初始化
    init:function(options){
        this.el = options.el;
        this.data = options.data;

        //使用分页对象进行数据渲染
        paging.init({"data":this.data,"el":this.el});
    },
    // 单行删除
    deleteTr:function(){
        var that = this;
        var $delete_tr = $(".tpl-table-black-operation-del");
        for(var i = 0; i < $delete_tr.length; i++){
            $delete_tr[i].onclick = function(){
                $('#delete-modal').modal({
                    relatedTarget: this,
                    onConfirm: function(e){
                        var index = $(this.relatedTarget).parents("tr").data("id");
                        // 删除当前行
                        $(this).parents("tr").remove();
                        // 更新数据
                        that.data.splice(index,1);
                        // 重新写入分页
                        paging.init({"data":that.data,"el":that.el});
                        $("#delete-modal").modal("close");
                    },
                    onCancel: function(e) {
                        $("#delete-modal").modal("close");
                    }
                });
            }
        }
    },
    // 全选
    selectAll:function(){
        var that = this;
        $("#select_all").on("click",function(){
            if($("#select_all").prop("checked") == true){
                that.is_select = true;
            }else{
                that.is_select = false;
            }
            var $tr = $(that.el).children("tbody").children("tr");
            var _len = $tr.length;
            for(var i = 0; i < _len; i++){
                var item = $tr[i];
                if(that.is_select == true){
                    $(item).find("input:checkbox").prop("checked",true);
                }else{
                    $(item).find("input:checkbox").prop("checked",false);
                }
            }
        })
    },
    // 删除多选
    delGroup:function(){
        var that = this;
        var del_tr = document.getElementById("del_tr");
        del_tr.onclick = function(){
            $('#delete-modal').modal({
                relatedTarget: this,
                onConfirm: function(e) {
                    var indexArr = [];
                    var $tr = $(that.el).children("tbody").children("tr");
                    var _len = $tr.length;
                    for(var i = 0; i < _len; i++){
                        var item =$tr[i];
                        if($(item).find("input:checkbox").prop("checked") == true){
                            indexArr.push(i);
                        }
                    }
                    for(var i = indexArr.length - 1; i >= 0; i--){
                        // 删除选中行
                        $("tr[data-id="+indexArr[i]+"]").remove();
                        // 更新数据
                        that.data.splice(indexArr[i],1);
                    }
                    // 重新写入分页
                    paging.init({"data":that.data,"el":that.el});
                    if(indexArr.length == _len){
                        $("#select_all").prop("checked",false);
                    }

                    $("#delete-modal").modal("close");
                },
                onCancel: function(e) {
                    $("#delete-modal").modal("close");
                }
            });
        }
    },
    // 新增行
    addRow:function(){
        var that = this;
        var add_role = document.getElementById("add_role");
        add_role.onclick = function(){
            that.addModalInit("#add_modal");
            //生成随机五位ID赋值到input中
            $('#role_id').val(that.produceId());
            //jstree操作
            that.jsTreeShow("#add_jstree");
            that.jsTreeChange("#add_jstree","#add_authorization");

            that.addModalChange();
        }
    },
    addModalInit:function(obj){
        $("#role_id").val("");
        $("#role_name").val("");
        $("add_authorization").val("");
    },
    addModalChange:function(){
        var that = this;
        $("#add-modal").modal({
                relatedTarget: this,
                onConfirm: function(e) {
                    var info = {
                        "id":e.data[0],
                        "name":e.data[1],
                        "authorization":that.selecetArr(e.data[2])
                    };

                    //新增数据到data
                    that.data.unshift(info);
                    //重新加载页面
                    paging.init({"data":that.data,"el":that.el});
                    //隐藏模态弹窗
                    $("#add-modal").modal("close");
                },
                onCancel: function(e) {
                    $("#add-modal").modal("close");
                }
            });
    },
    //生成五位不含零的随机数作为ID
    produceId:function(){
        var old = Math.ceil((Math.random() * 90000 + 10000)).toString();
        var id = old.replace(/0/g,"2");
        return id;
    },
    selecetArr:function(str){
        var strArr = str.split(",");
        var selectArr = [];
        for(var i = 0; i < strArr.length; i++){
            var item = parseInt(strArr[i]);
            selectArr.push(item);
        }
        return selectArr;
    },
    // 编辑
    modifyPw:function(){
        var that = this;
        $('.widget-body.am-fr').find('.tpl-table-black-operation-mod.set-pw').
        on('click', function() {
            //获取当前数据
            var index = $(this).parents("tr").attr("data-id");
            that.assignmentValue(index);
            //初始渲染modal
            that.modifyMadalShow(index);
            //显示modal
            that.modifyMadalChange(index);
            // $('#modify-modal').on('closed.modal.amui', function() {
            //     $(this).removeData('amui.modal');
            // });

        });
    },
    assignmentValue:function(index){
        var that = this;
        var role_name = that.data[index].name;
        var authorization = that.data[index].authorization;
        //填充数据
        $("#modify_role_name").val(role_name);
        $("#modify_authorization").val(authorization);
    },
    modifyMadalShow:function(index){
        var that = this;
        $('#modify-modal').on('open.modal.amui', function(){
                //jsTree初始化
                that.jsTreeShow("#modify_jstree");
                that.jsTreeChange("#modify_jstree","#modify_authorization");
                that.jsTreeLoad("#modify_jstree",that.data[index].authorization);
            });
    },
    modifyMadalChange:function(index){
        var that = this;
        $('#modify-modal').modal({
            relatedTarget: this,
            onConfirm: function(e) {
                var info = {
                    "name":e.data[0],
                    "authorization":that.selecetArr(e.data[1])
                }

                // 修改数据
                that.data[index].name = info.name;
                that.data[index].authorization = info.authorization;
                //重新加载页面
                paging.init({"data":that.data,"el":that.el});
                // $(this).removeData('amui.modal');
                $("#modify-modal").modal("close");
            },
            onCancel: function(e) {
                $("#modify-modal").modal("close");
            }
        });
    },
    //显示jstree
    jsTreeShow:function(obj){
        var that = this;
        //清空实例
        $.jstree.destroy(obj);
        $(obj).jstree({
            "types":{
                "default":{
                    "icon":"glyphicon glyphicon-leaf"
                },
                "demo":{
                    "icon":"glyphicon glyphicon-ok"
                }
            },
            "plugins":["checkbox","types"],
            "core":{
                "data":treeData,
            }
        });
    },
    //监听jstree改变事件
    jsTreeChange:function(obj,target){
        $(obj).on("changed.jstree",function(e,data){
            $(target).val(data.selected);
        });
    },
    //jstree加载时改变select选项事件
    jsTreeLoad:function(obj,selectData){
        $(obj).on("loaded.jstree",function(e,data){
            var inst = data.instance;  
            if(selectData){
                for(var i = 0; i < selectData.length; i++){
                var item = selectData[i];
                inst.select_node(item);
            }
            }
        });
    },

}

var paging = {
        el:"",  //挂载点
        pageData:[],  //转化为可直接使用的DOM数据
        dataCount:0,  //数据总条数
        pageSize:10,  //每页显示数据数
        pageCount:0,  //总页数
        currentPage:1,  //当前页，默认为1
        init:function(options){
            this.el = options.el;
            this.pageData = this.dataToDom(options.data);
            this.dataCount = options.data.length;
            this.pageCount = Math.ceil(options.data.length / this.pageSize);

            //数据加载
            this.currentDisplay();
        },
        // 将传入数据转化为dom
        dataToDom:function(data){
            var domArr = [];
            for(var i = 0; i < data.length; i++){
                var dom = "<tr data-id='"+i+"'>" + 
                        "<td><input type='checkbox' value='"+i+"'></td>" + 
                        "<td>"+(i+1)+"</td>" + 
                        "<td>"+data[i].id+"</td>" + 
                        "<td>"+data[i].name+"</td>" + 
                        "<td>" +
                            '<div class="tpl-table-black-operation">'+
                               '<a href="javascript:;" class="tpl-table-black-operation-del delete-op" data-index='+i+'>'+
                                    '<i class="am-icon-trash"></i>删除'+
                                '</a>'+
                                '<a href="javascript:;" class="tpl-table-black-operation-mod set-pw" data-index='+i+'>'+
                                    '<i class="am-icon-pencil"></i>编辑'+
                                '</a>'+
                            '</div> '+
                        "</td>" + 
                    "</tr>";
                domArr.push(dom);
            }
            return domArr;
        },
        // 页码按钮初始化
        pagingButton:function(){
            var pageN = "";
            var that = this;
            if(that.pageCount == 1){
                var pageNav = "";
            }else if(that.pageCount <= 5){
                for(var i = 1; i <= that.pageCount; i++){
                    pageN += "<li id='page"+i+"' selectPage='"+i+"'><a href='#'>"+i+"</a></li>";  
                   //注意此处使用了自定义属性selectPage
                }
                var pageNav = that.getPageN(pageN);
            }else if(that.pageCount > 5){
                if(that.currentPage <= 3){
                    for(var i = 1; i < 5; i++){
                        pageN += "<li id='page"+i+"' selectPage='"+i+"'><a href='#'>"+i+"</a></li>";
                    }
                    pageN += "<li class='disabled' selectPage='dots'><span>···</span></li>" + "<li id='page"+that.pageCount+"' selectPage='"+that.pageCount+"'><a href='#'>"+that.pageCount+"</a></li>";
                }else if(that.currentPage > 3 && that.currentPage < that.pageCount - 2){
                    pageN = "<li id='page1' selectPage='1'><a href='#'>1</a></li>" + "<li class='disabled' selectPage='dots'><span>···</span></li>";
                    for(var i = parseInt(that.currentPage) - 2; i <= parseInt(that.currentPage) + 2; i++){
                        pageN += "<li id='page"+i+"' selectPage='"+i+"'><a href='#'>"+i+"</a></li>";
                    }
                    pageN += "<li class='disabled' selectPage='dots'><span>···</span></li>" + "<li id='page"+that.pageCount+"' selectPage='"+that.pageCount+"'><a href='#'>"+that.pageCount+"</a></li>";
                }else if(that.currentPage >= that.pageCount - 2){
                    pageN = "<li id='page1' selectPage='1'><a href='#'>1</a></li>" + "<li class='disabled' selectPage='dots'><span>···</span></li>";
                    for(var i = that.pageCount - 4; i <= that.pageCount; i++){
                        pageN += "<li id='page"+i+"' selectPage='"+i+"'><a href='#'>"+i+"</a></li>";
                    }
                }
                var pageNav = that.getPageN(pageN);
            }

            $("#page").html("");
            $("#page").append(pageNav)  //将pageNav append 到挂载点上
        },
        getPageN:function(content){
            return "<ul class='am-pagination'>" + "<li selectPage='up'><a href='#''><span class='am-icon-angle-double-left'></span></a></li>" + content + "<li selectPage='down'><a href='#'><span class='am-icon-angle-double-right'></a></li>" + "</ul>";
        },
        // 显示当前页数据
        // 初始化显示第一页数据
        // currentPage = 1
        modify_jstree:function(){
            var that = this;
            $(that.el).children("tbody").empty();
            var firstData = (that.currentPage - 1) * that.pageSize;
            //防止最后一页没有数据
            //没有数据就重新加载到新的最后一页
            if(!that.pageData[firstData]){
              that.currentPage = that.currentPage - 1;
            }
            for(var i = (that.currentPage - 1) * that.pageSize; i < that.pageSize * that.currentPage; i++){
                $(that.el).children("tbody").append(that.pageData[i]);  //将当前页的数据append到表格上
            }

            //加载button对应事件
            that.pagingButton(); 
            that.checkCritical();
            that.selectDisplay();
            $("#page"+that.currentPage+"").addClass("am-active");  //当前页更改样式

            //加载操作事件
            roles_manager.deleteTr();
            roles_manager.selectAll();
            roles_manager.delGroup();
            roles_manager.addRow();
            roles_manager.modifyPw();

        },
        // 显示选中页的内容
        selectDisplay:function(el){
            var that = this;
            $("li").click(function(){
               //对当前点击button的属性selectPage作出判断
               if($(this).attr("selectPage") == "up"){
                     if(that.currentPage == 1){
                        return;
                     }else{
                        that.currentPage--;
                        $("li").removeClass("am-active");
                        that.currentDisplay();
                        that.checkCritical();
                     }
               }else if($(this).attr("selectPage") == "down"){
                    if(that.currentPage == that.pageCount){
                        return;
                    }else{
                        that.currentPage++;
                        $("li").removeClass("am-active");
                        that.currentDisplay();
                        that.checkCritical();
                    }
               }else{
                    $("li").removeClass("am-active");
                    that.currentPage = $(this).attr("selectPage");
                    that.currentDisplay();
                    that.checkCritical();
                }
            })
        },
        // 检查临界值，用于判断是否在第一页和最后一页
        checkCritical:function(){
            var that = this;
            if(that.currentPage == 1){
                $("li:first").addClass("am-disabled");
            }else if(that.currentPage == that.pageCount){
                $("li:last").addClass("am-disabled");
            }else{
                $("li").removeClass("am-disabled");
            }
        }
    }

roles_manager.init({"data":data,"el":"#example-r"});